package com.ustcinfo.ishare.esCURD;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Shinelon on 2017/12/26.
 * 封装es 对于索引和document 的删除操作
 */
public class ESDelete {
    private static final Logger LOGGER  = LoggerFactory.getLogger(ESDelete.class);

    /**
     * 根据 id 删除 文档
     * @param transportClient
     * @param indexName     索引名
     * @param type          类型
     * @param id            id
     */
    public void deleteDocumentById(TransportClient transportClient,String indexName, String type, String id){
        DeleteResponse deleteResponse = transportClient.prepareDelete(indexName,type,id).execute().actionGet();
        if (!deleteResponse.isFragment())
            System.out.println("document 删除成功！");
    }

    /**
     * 根据索引名 删除索引
     * @param transportClient
     * @param indexName
     */
    public void deleteIndex(TransportClient transportClient,String indexName){
        IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest(indexName);
        IndicesExistsResponse indicesExistsResponse = transportClient.admin().indices().exists(indicesExistsRequest).actionGet();
        if (indicesExistsResponse.isExists()){
            DeleteIndexResponse deleteIndexResponse = transportClient.admin().indices().prepareDelete(indexName).execute().actionGet();
            if (deleteIndexResponse.isAcknowledged())
                System.out.println("索引删除成功！");
        }else {
            System.out.println("该索引不存在！");
        }
    }

}
